﻿using CommonDevelop;
using CommonDevelop.DB;
using CommonFP;
using ManageDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace ManageRepository
{
    /// <summary>
    /// 模块配置数据层接口
    /// </summary>
    public interface IModuleRepository : IBase<Base_Module>
    {

    }

    /// <summary>
    /// 模块配置数据层
    /// </summary>
    public class ModuleRepository : DBBase<Base_Module>, IModuleRepository
    {
        public override Expression<Func<Base_Module, bool>> WhereKeyWord(string keyword)
            => t => t.ModuleCode.Contains(keyword)
            || t.FullName.Contains(keyword)
            || t.TargetEnReg.Contains(keyword);

        public override IEnumerable<TVO> GetPull<TVO>(Base_Module en)
        {
            if (en == null)
                return base.GetPull<TVO>(en);

            if (typeof(TVO).Equals(typeof(Base_Module)))
            {
                List<Base_Module> result = new List<Base_Module>();
                en.ModuleId.ToOption()
                    .Map(a => this.GetList(d => d.ParentId == a))
                    .ForEach(a => result.AddRange(a));

                return result.Cast<TVO>().ToList();
            }
            else
                return base.GetPull<TVO>(en);
        }

        public override IEnumerable<Base_Module> GetPush<TVO>(TVO en)
        {
            var result = base.GetPush<TVO>(en);
            if (en == null)
                return result;

            if (typeof(TVO).Equals(typeof(Base_Module)))
            {
                (en as Base_Module)
                    .ToOption()
                    .Map(a => this.GetEntity(m => m.ModuleId == a.ParentId, false))
                    .ForEach(a => result.Append(a));

                return result;
            }
            else
                return result;
        }
    }
}
